package com.erf.session;

import io.netty.channel.Channel;

import java.security.SecureRandom;
import java.util.Collection;
import java.util.HashMap;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhangzy
 * @date 2022/7/5
 */
public class Session {
    public static HashMap<String, HashMap<String, Channel>> userChannelMap = new HashMap<>();

    public static ReentrantLock userChannelMapLock = new ReentrantLock();

    private static final SecureRandom RANDOM = new SecureRandom();

    public static void put(String userName, Channel channel) {
        userChannelMapLock.lock();
        try {
            HashMap<String, Channel> stringChannelHashMap = userChannelMap.get(userName);
            if (stringChannelHashMap == null) {
                stringChannelHashMap = new HashMap<>();
                stringChannelHashMap.put(channel.id().asShortText(), channel);
                userChannelMap.put(userName, stringChannelHashMap);
            } else {
                stringChannelHashMap.put(channel.id().asShortText(), channel);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            userChannelMapLock.unlock();
        }

    }

    public static void remove(String userName, String channelId) {
        userChannelMapLock.lock();
        try {
            HashMap<String, Channel> stringChannelHashMap = userChannelMap.get(userName);
            if (stringChannelHashMap != null) {
                stringChannelHashMap.remove(channelId);
                if (stringChannelHashMap.size() == 0) {
                    userChannelMap.remove(userName);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            userChannelMapLock.unlock();
        }
    }

    public static Channel getRandomChannel(String userName) {
        HashMap<String, Channel> stringChannelHashMap = userChannelMap.get(userName);
        if (stringChannelHashMap != null) {
            int size = stringChannelHashMap.size();
            Collection<Channel> values = stringChannelHashMap.values();
            int index = RANDOM.nextInt(size);
            Object[] objects = values.toArray();
            return (Channel) objects[index];
        }
        return null;
    }

}
